import { message } from "ant-design-vue";

export default function OperationHook(state: Base.GeneraDataType) {
  const { formDataRef, passData, emit, initForm } = state;

  const submitHandle = () => {
    formDataRef.value.validate().then(() => {
      if (!passData.value.beginTime) return message.error("请选择生效时间!");
      emit("editBaseSubmit", true);
    });
  };
  const addWeightSegmentHandle = () => {
    const flag = passData.value.weightSegmentList.some((t: any) => (t.minValue !== 0 && !t.minValue) || (t.maxValue !== 0 && !t.maxValue) || !t.type);
    if (flag) return message.error("请先填写完整当前重量段，再添加!");
    passData.value.weightSegmentList.push({
      minValue: undefined,
      maxValue: undefined,
      type: undefined
    });
    passData.value.itemList = [];
  };
  const deleteWeightSegmentHandle = (index: number) => {
    passData.value.weightSegmentList.splice(index, 1);
  };
  const addRateHandle = () => {
    const target = {
      countryList: [],
      region: undefined,
      city: undefined,
      detailsList: []
    };
    target.detailsList = passData.value.weightSegmentList.map(() => {
      return {
        unitPrice: undefined,
        amount: undefined,
        firstWeight: undefined,
        firstPrice: undefined,
        continuationWeight: undefined,
        continuationPrice: undefined
      };
    });
    passData.value.itemList.push(target);
  };
  const deleteRateHandle = (index: number) => {
    passData.value.itemList.splice(index, 1);
  };
  const cancelHandle = () => {
    passData.value.itemList = initForm.value.itemList;
    passData.value.weightSegmentList = initForm.value.weightSegmentList;
    emit("update:visible", false);
  };
  return {
    submitHandle,
    addWeightSegmentHandle,
    deleteWeightSegmentHandle,
    addRateHandle,
    deleteRateHandle,
    cancelHandle
  };
}
